/**
 * 
 */
package com.ideazd.api.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ideazd.api.model.AppUpdate;
import com.ideazd.api.model.FeedBack;
import com.ideazd.api.model.LoginLog;
import com.ideazd.api.model.SentAddress;
import com.ideazd.api.model.SmsCode;
import com.ideazd.api.model.SysAreas;
import com.ideazd.api.model.Topic;
import com.ideazd.api.model.User;
import com.ideazd.api.model.dto.RetDTO;
import com.ideazd.api.msm.SentMessage;
import com.ideazd.api.service.UserService;
import com.ideazd.api.tools.DateUtil;
import com.ideazd.api.tools.SysUtil;
import com.ideazd.api.util.RandomUtil;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;

/**
 * @author yzz
 * @create 2016年3月24日 上午10:47:22
 */
@ControllerBind(controllerKey="user")
public class UserController extends Controller {
	private static final Logger log = Logger.getLogger(UserController.class);
	private UserService userService = new UserService();
	
	/**
	 * 获取验证码
	 */
	public void getSmsCode(){
		String phone = getPara("phone");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(phone)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		try {
			
			SmsCode sms = SmsCode.dao.findFirst("select count(*) as 'count' from sta_smscode where phone = '"+phone+"' and sendtime > curdate() and sendtime < now() ");
			
			if(Integer.parseInt(sms.get("count").toString())>5){
				ret.setCode("-3");
				ret.setMsg("你已超过验证码发送上限");
				renderJson(ret);
				return;
			}
			
			
			String verifyCode =RandomUtil.randomFor6();//自定义验证码
			SentMessage.sentVerifyCode(phone,verifyCode);//发送短信
			
		   SmsCode smsCode = new SmsCode()
		   .set("smsid", SysUtil.getUUID())
		   .set("phone", phone)
		   .set("smstype", "0")
		   .set("checkcode", verifyCode)
		   .set("sendtime", new Date());
			
			if(smsCode.save()){
				ret.setCode("0");
				ret.setMsg("成功");
			}
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	/**
	 * 用户登录
	 */
	
	public void login(){
		String account = getPara("account");
		String useType = getPara("useType");
		String smsCode = getPara("smsCode");
		String ip = getPara("ip");
		String gender = getPara("gender");
		String nickName = getPara("nickName");
		String headPortrait = getPara("headPortrait");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(account) || StrKit.isBlank(useType)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		
		
		try {
			
			if("1".equals(useType)){
				
				if(StrKit.isBlank(smsCode)){
					ret.setCode("-2");
					ret.setMsg("必传参数不允许为空");
					renderJson(ret);
					return;
				}
				
				if(!account.equals("18515064839")){
					SmsCode checkCode = SmsCode.dao.findFirst("select * from sta_smscode where phone = '"+account+"' and checkcode = '"+smsCode+"'");
					
					if(null == checkCode){
						ret.setCode("-3");
						ret.setMsg("验证码输入有误");
						renderJson(ret);
						return;
					}else{
						
						if((new Date().getTime() - checkCode.getDate("sendtime").getTime()) > 600000){
							ret.setCode("-4");
							ret.setMsg("验证码已过期");
							renderJson(ret);
							return;
						}
						
					}
					
				}else{
					
					if(!smsCode.equals("123456")){
						ret.setCode("-3");
						ret.setMsg("验证码输入有误");
						renderJson(ret);
						return;
					}
				}
				nickName = account;
			}
			
			User user = userService.findUserByAccount(account);
			
			if(null == user){
				user = new User();
				String userId = SysUtil.getUUID();
				user.set("useid", userId);
				user.set("account", account);
				user.set("nickname", nickName);
				
				if(!StrKit.isBlank(headPortrait)){
					user.set("gender", gender);
				}
				
				
				if(!StrKit.isBlank(headPortrait)){
					user.set("headportrait", headPortrait);
				}
				
				user.set("userstatus", "0");
				user.set("logintime", new Date());
				user.set("usetype", useType);
				user.save();
			}
			
			LoginLog log = new LoginLog();
			log.set("logid", SysUtil.getUUID());
			log.set("useid", user.get("useid"));
			log.set("logtime", new Date());
			log.set("logip", ip);
			log.save();
			
			ret.put("useId", user.get("useid"));
			ret.put("account", user.get("account"));
			ret.put("nickName", SysUtil.validateStr(user.get("nickname")));
			ret.put("gender", SysUtil.validateStr(user.get("gender")));
			ret.put("headPortrait", SysUtil.validateStr(user.get("headportrait")));
			ret.put("userStatus", SysUtil.validateStr(user.get("userstatus")));
			ret.put("userType", user.get("usetype"));
			
            boolean unread = false;
			Topic post = Topic.dao.findFirst("select SUM(unread) as count from sta_topic where createid = '"+user.get("useid")+"'");
			
			if(null != post.get("count")){
				System.out.println(post.get("count"));
				if(Double.parseDouble(post.get("count").toString()) > 0){
					unread = true;
				}
			}
			
			
			
			ret.put("unread", unread);
			ret.setCode("0");
			ret.setMsg("成功");
			
			
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	/**
	 * 获取用户详情
	 */
	public void getUserDetail(){
		String useId = getPara("useId");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(useId)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		try {
			User user = userService.findUserById(useId);
			
			ret.put("useId", SysUtil.validateStr(user.get("useid")));
			ret.put("account", SysUtil.validateStr(user.get("account")));
			ret.put("nickName", SysUtil.validateStr(user.get("nickname")));
			ret.put("gender", SysUtil.validateStr(user.get("gender")));
			ret.put("phone", SysUtil.validateStr(user.get("phone")));
			ret.put("personality", SysUtil.validateStr(user.get("personality")));
			ret.put("headPortrait", SysUtil.validateStr(user.get("headportrait")));
			ret.put("userStatus", SysUtil.validateStr(user.get("userstatus")));
			ret.put("useType", SysUtil.validateStr(user.get("usetype")));
			
			ret.setCode("0");
			ret.setMsg("成功");
			
			
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	/**
	 * 修改用户信息
	 */
	public void editUserInfo(){
		String useId = getPara("useId");
		String headPortrait = getPara("headPortrait");
		String nickName = getPara("nickName");
		String personality = getPara("personality");
		String gender = getPara("gender");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(useId)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try {
			
			if(!StrKit.isBlank(headPortrait)){
				
				Map<String, String> imaPath = SysUtil.uploadImg(getRequest(),headPortrait,"/upload/userheadPortrait"+"/"+useId+"/images"+"/"+DateUtil.formatDate(new Date(),"yyyyMMdd")+"/");
				
				headPortrait = imaPath.get("diskPath");
				
			}
			
			User user = User.dao.findById(useId);
			user.set("useid", useId);
			
			if(!StrKit.isBlank(nickName)){
				user.set("nickname", nickName);
			}
			
			if(!StrKit.isBlank(gender)){
				user.set("gender", gender);
			}
			
			if(!StrKit.isBlank(personality)){
				user.set("personality", personality);
			}
			
			if(!StrKit.isBlank(headPortrait)){
				user.set("headportrait", headPortrait);
			}
			
			user.update();
			
			ret.put("useId", SysUtil.validateStr(user.get("useid")));
			ret.put("gender", SysUtil.validateStr(user.get("gender")));
			ret.put("nickName", SysUtil.validateStr(user.get("nickname")));
			ret.put("personality", SysUtil.validateStr(user.get("personality")));
			ret.put("headPortrait", SysUtil.validateStr(user.get("headportrait")));
			ret.setCode("0");
			ret.setMsg("成功");
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	
	/**
	 * 建议反馈
	 */
	public void sendFeedBack(){
		String useId = getPara("useId");
		String feeInfo = getPara("feeInfo");
		String contactMode = getPara("contactMode");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(useId) || StrKit.isBlank(feeInfo) || StrKit.isBlank(contactMode)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		try {
			FeedBack feedBack = new FeedBack();
			feedBack.set("feeid", SysUtil.getUUID());
			feedBack.set("useid", useId);
			feedBack.set("feeinfo", feeInfo);
			feedBack.set("contactmode", contactMode);
			feedBack.set("createtime", new Date());
			feedBack.set("handlestate", "0");
			feedBack.save();
			
			ret.setCode("0");
			ret.setMsg("成功");
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	/**
	 * 提醒通知
	 */
	public void setOpenSms(){
		String useId = getPara("useId");
		String opneSms = getPara("opneSms");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(useId) || StrKit.isBlank(opneSms)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		try {
			User user = new User();
			user.set("useid", useId);
			user.set("opensms", opneSms);
			
			ret.setCode("0");
			ret.setMsg("成功");
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	//添加地址
	public void addAddress(){
		String useId = getPara("useId");
		String receiver =  getPara("receiver");
		String phone =  getPara("phone");
		String provinceCode =  getPara("provinceCode");
		String cityCode =  getPara("cityCode");
		String districtCode =  getPara("districtCode");
		String street =  getPara("street");
		String zipCode =  getPara("zipCode");
		String setDefault = getPara("setDefault");
		String isDefault = "0";
        RetDTO ret = new RetDTO();
        
        if(StrKit.isBlank(useId) || StrKit.isBlank(provinceCode) || StrKit.isBlank(cityCode) || StrKit.isBlank(districtCode)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
        
		
		try{
			
			List<SentAddress> purchaseSentAddressList = SentAddress.dao.find("select * from sta_sent_address where useid = '"+useId+"'");
			
			if(purchaseSentAddressList.size() == 5){
				ret.setCode("-3");
				ret.setMsg("收货地址过多");
				renderJson(ret);
				return;
			}
			
			//是否默认
			if("true".equals(setDefault)){
				
				if(Db.update("update sta_sent_address set isdefault = '0' where useid = '"+useId+"'") < 1){
					ret.setCode("-4");
					ret.setMsg("设置默认地址有误");
				}
				isDefault = "1";
			}
			
			SentAddress sentAddress = new SentAddress()
			.set("id",SysUtil.getUUID() )
			.set("useid", useId)
			.set("provincecode", provinceCode)
			.set("citycode", cityCode)
			.set("countycode", districtCode)
			.set("receiverstreet", street)
			.set("isdefault",isDefault )
			.set("zipcode", zipCode)
			.set("telephone",phone)
			.set("receivername", receiver)
			.set("createdate", new Date());
			
			if(sentAddress.save()){
				ret.setCode("0");
				ret.setMsg("添加成功");
			}
			
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	//获取地址列表
	public void getAddressList(){
		String useId = getPara("useId");
		
		Map<Object,Object> rets = new HashMap<Object,Object>();
		
		try {
			
			if(StrKit.isBlank(useId)){
				rets.put("code","-2");
				rets.put("msg","必传参数不允许为空");
				renderJson(rets);
				return;
			}
			
			
			//获取首页数据
			List<SentAddress> addressList = SentAddress.dao.find("select * from sta_sent_address where useid = '"+useId+"'");
			List<Map<Object,Object>> lists = new ArrayList<Map<Object,Object>>();
			
			for(SentAddress address:addressList){
				
				Map<Object,Object> ret = new HashMap<Object,Object>();
				ret.put("addressId", address.get("id"));
				ret.put("receiver", address.get("receivername"));
				ret.put("phone", address.get("telephone"));
				ret.put("provinceCode", address.get("provincecode"));
				ret.put("cityCode", address.get("citycode"));
				ret.put("districtCode", address.get("countycode"));
				
				//省市县
				SysAreas province = SysAreas.dao.findById(address.get("provincecode"));
				SysAreas city = SysAreas.dao.findById(address.get("citycode"));
				SysAreas distrct = SysAreas.dao.findById(address.get("countycode"));
				
				ret.put("provinceName", province.get("area_name"));
				ret.put("cityName", city.get("area_name"));
				ret.put("districtName", distrct.get("area_name"));
				ret.put("street", address.get("receiverstreet"));
				ret.put("zipCode", address.get("zipcode"));
				ret.put("isDefault", SysUtil.getBoolean(address.get("isdefault").toString()));
				lists.add(ret);
			}
			
			rets.put("data", lists);
			rets.put("code","0");
			rets.put("msg","数据获取完成");
		} catch (Exception e) {
			rets.put("code","-1");
			rets.put("msg",e.getMessage());
		}
		renderJson(rets);
		return;
	}
	
	
	//删除地址
	public void delAddress(){
		String addressId = getPara("addressId");
        RetDTO ret = new RetDTO();
		
		try{
			
			if(SentAddress.dao.deleteById(addressId)){
				ret.setCode("0");
				ret.setMsg("删除成功");
			}
			
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	//修改地址
	public void updateAddress(){
		String addressId = getPara("addressId");
		String useId = getPara("useId");
		String receiver =  getPara("receiver");
		String phone =  getPara("phone");
		String provinceCode =  getPara("provinceCode");
		String cityCode =  getPara("cityCode");
		String districtCode =  getPara("districtCode");
		String street =  getPara("street");
		String zipCode =  getPara("zipCode");
		String setDefault = getPara("setDefault");
		String isDefault = "0";
        RetDTO ret = new RetDTO();
		
		try{
			
			if(StrKit.isBlank(useId) ||StrKit.isBlank(addressId) || StrKit.isBlank(provinceCode) || StrKit.isBlank(cityCode) || StrKit.isBlank(districtCode)){
				ret.setCode("-2");
				ret.setMsg("必传参数不允许为空");
				renderJson(ret);
				return;
			}
			
			//是否默认
			if("true".equals(setDefault)){
				
				if(Db.update("update sta_sent_address set isdefault = '0' where useid = '"+useId+"'") < 1){
					ret.setCode("-4");
					ret.setMsg("设置默认地址有误");
				}
				isDefault = "1";
			}
			
			String updateSlq = "update sta_sent_address set provincecode = '"+provinceCode+"',citycode = '"+cityCode+"',countycode = '"+districtCode+"', receiverstreet='"+street+"',isdefault='"+isDefault+"',zipcode='"+zipCode+"',telephone='"+phone+"',receivername='"+receiver+"' where id = '"+addressId+"'";
			
			if(Db.update(updateSlq) > 0){
				ret.setCode("0");
				ret.setMsg("修改成功");
			}
				
		}catch(Exception e){
			ret.setCode("10003");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
	/**
	 * 获取版本
	 */
	public void updateVersion(){
		RetDTO ret = new RetDTO();
		try{
			AppUpdate android_version = AppUpdate.dao.findFirst("select * from sta_app_update");
			if(android_version!=null){
					ret.put("androidVersion", android_version.get("android_version"));
					ret.put("androidApkUrl", android_version.get("android_apk_url"));
					ret.put("iosVersion", android_version.get("ios_version"));
					ret.put("iosIpaUrl", android_version.get("ios_apk_url"));
					ret.setCode("0");
					ret.setMsg("数据获取完成");
			}else{
				ret.setCode("-1");
				ret.setMsg("服务器错误");
			}
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
	}
	

}
